import { ProFormDigit, ProFormDependency } from '@ant-design/pro-form';
import { useState, useRef, useEffect } from 'react';
import { Form, Segmented, message } from 'antd';
import { useDispatch, useModel } from 'umi';
import FormLabelTip from '@/components/FormLabelTip';
import CommonUpload from '@/components/CommonUpload';
import { UPLOAD_FOLDER } from '@/constants/global.const';
import MultiCrops from 'react-multi-crops';
import { values } from 'lodash';
import { throttle } from '@/utils/utils';

import WrapperForm from '../../wrapperForm';
import FormJumpPage from '../../../costomFields/formJumpPage';
import { rules, PAD_STYLE, coordinateDataItem } from '..';
import styles from './index.less';

import type { HotspotValue, coordinateType } from '..';
import type { Rule } from 'antd/lib/form';

interface IHotspotFormProps {
  data: HotspotValue;
}

const HotspotForm: React.FunctionComponent<IHotspotFormProps> = (props) => {
  const { initialState } = useModel('@@initialState');
  const { imgPrefix } = initialState as { imgPrefix: string };

  const dispatch = useDispatch();
  const imgRef = useRef<any>();
  const wrapRef = useRef<any>(); //实例 WrapperForm，修改绑定的表单数据
  const [coordinateSource, setCoordinateSource] = useState<coordinateType[]>([]);
  const [formRef, setFormRef] = useState<any>();

  useEffect(() => {
    if (wrapRef.current) {
      setFormRef(wrapRef.current.formRef);
      setCoordinateSource(props.data.coordinates);
    }
  }, [wrapRef.current]);

  // 将坐标--数值换算成具体比例
  const formatRate = (coordinatesum: coordinateType[]) => {
    const coordinatesBro: coordinateType[] = [];
    coordinatesum.forEach((item, index) => {
      if (imgRef && imgRef.current) {
        const width = imgRef.current.offsetWidth;
        const height = imgRef.current.offsetHeight;
        coordinatesBro.push({
          ...item,
          xRate: Number((item.x / width).toFixed(3)),
          yRate: Number((item.y / height).toFixed(3)),
          widthRate: Number((item.width / width).toFixed(3)),
          heightRate: Number((item.height / height).toFixed(3)),
          aspectRate: Number((width / height).toFixed(3)), //图片宽高比
        });
      } else {
        coordinatesBro.push({
          ...item,
          aspectRate: 1, //图片宽高比
        });
      }
    });
    return coordinatesBro;
  };

  const limintCoordinate = throttle(() => {
    message.error('热区增加上限为15个');
  });

  // 增加区域
  const changeCoordinate = (
    coordinate: coordinateType,
    index: number,
    _coordinates: coordinateType[],
  ) => {
    // 最多增加15个热区
    if (_coordinates.length > 15) {
      limintCoordinate();
      return;
    }

    // 如何区分增加元素还是改变元素
    if (_coordinates.length > coordinateSource.length) {
      // 新增时向链接组件--增加一条数据
      const coordinatesBroNew = [...formRef.getFieldValue('coordinateData'), coordinateDataItem];
      formRef.setFieldsValue({ coordinateData: coordinatesBroNew });
    }
    setCoordinateSource(formatRate(_coordinates));
    // 手动更新表单和触发redux;
    formRef.setFieldValue('coordinates', formatRate(_coordinates));
    dispatch({
      type: 'decoration/updateData',
      payload: { coordinates: formatRate(_coordinates) },
    });
  };

  // 删除区域
  const deleteCoordinate = (
    coordinate: coordinateType,
    index: number,
    _coordinates: coordinateType[],
  ) => {
    // 删除时向链接组件--减少一条数据
    const coordinatesBro = formRef.getFieldValue('coordinateData');
    coordinatesBro.splice(index, 1);
    formRef.setFieldValue('coordinateData', coordinatesBro);
    dispatch({
      type: 'decoration/updateData',
      payload: { coordinateData: coordinatesBro },
    });
    setCoordinateSource(formatRate(_coordinates));
    // 手动更新表单和触发redux;
    formRef.setFieldValue('coordinates', formatRate(_coordinates));
    dispatch({
      type: 'decoration/updateData',
      payload: { coordinates: formatRate(_coordinates) },
    });
  };

  return (
    // @ts-ignore
    <WrapperForm<HotspotValue> ref={wrapRef} reducerName="updateData" {...props}>
      <Form.Item
        label={<FormLabelTip title="图片" subTitle={`格式支持JPG、PNG，大小不超过10MB`} />}
        name="imageUrl"
        required
        rules={rules.imageUrl as Rule[]}
      >
        <CommonUpload
          folder={UPLOAD_FOLDER.LOTTERYDRAW}
          maxSize={10240}
          accept={['.jpg', '.png']}
          extraInfo={false}
          needCrop={false}
        />
      </Form.Item>
      <ProFormDependency name={['imageUrl']}>
        {({ imageUrl }) => {
          if (imageUrl) {
            return (
              <Form.Item
                label={<FormLabelTip title="添加热区" subTitle={`鼠标左击并进行拖拽`} />}
                name="coordinates"
              >
                <div ref={imgRef} className={styles['image-body']}>
                  <MultiCrops
                    src={`${imgPrefix}${imageUrl}`}
                    width={360}
                    coordinates={coordinateSource}
                    onChange={changeCoordinate}
                    onDelete={deleteCoordinate}
                  />
                </div>
              </Form.Item>
            );
          }
          return <div className={styles['image-empty']}>请先上传图片</div>;
        }}
      </ProFormDependency>

      <Form.Item label="边距设置" name="padStyle" className={styles['segment-father']}>
        <Segmented options={values(PAD_STYLE)} />
      </Form.Item>

      <ProFormDigit
        required
        width={100}
        min={0}
        label="图片圆角"
        name="borderRadius"
        placeholder="请输入圆角"
        rules={rules.borderRadius as Rule[]}
      />

      <FormJumpPage
        isShowBtn={false}
        isShowImg={false}
        isShowTitle={false}
        name="coordinateData"
        label={'设置热区链接'}
      />
    </WrapperForm>
  );
};

export default HotspotForm;
